#include "DOF.h"

template<> DOF::GameObjectManager *Ogre::Singleton<DOF::GameObjectManager>::msSingleton = 0;

namespace DOF
{
	template<typename T> GameObject *GameObjectManager::createObject(Ogre::Vector3 pos, Ogre::Quaternion rot, Ogre::String name)
	{
		ID id;
		for(id = 0; m_GameObjectList.find(i); i++);

		if(name != "")
		{
			GameObjectMap::iterator i;

			for(i = m_GameObjectList.begin(); i != m_GameObjectList.end(); i++)
			{
				if(i->second->getName() == name)
					OGRE_EXCEPT(Ogre::Exception::ERR_DUPLICATE_ITEM, "GameObject with specified name '" + name + "' already exists!", "DOF::GameObjectManager::createObject()");
			}
		}

		T *newObject = new T(id, pos, rot, name);

		m_GameObjectList.insert(std::pair<ID, GameObject*>(id, newObject));

		return newObject;
	}

	void GameObjectManager::update(const Ogre::FrameEvent &evt)
	{
		GameObjectMap::iterator i;
		
		for(i = m_GameObjectList.begin(); i != m_GameObjectList.end(); i++)
		{
			GameObject *obj = i->second;

			obj->update(evt);
		}
	}

	bool GameObjectManager::destroyObject(ID id)
	{
		GameObjectMap::iterator i = m_GameObjectList.find(id);

		if(i != m_GameObjectList.end())
		{
			GameObject *obj = i->second;

			m_GameObjectList.erase(i);
			delete obj;

			return true;
		}

		return false;
	}

	void GameObjectManager::destroyAll(void)
	{
		GameObjectMap::iterator i;

		for(i = m_GameObjectList.begin(); i != m_GameObjectList.end(); i++)
		{
			GameObject *obj = i->second;

			m_GameObjectList.erase(i);
			delete obj;
		}
	}

	GameObject *GameObjectManager::getObjectByID(ID id) const
	{
		GameObjectMap::const_iterator i = m_GameObjectList.find(id);

		if(i != m_GameObjectList.end())
			return i->second;

		return 0;
	}

	GameObject *GameObjectManager::getObjectByName(Ogre::String name)
	{
		GameObjectMap::iterator i;

		for(i = m_GameObjectList.begin(); i != m_GameObjectList.end(); i++)
			if(i->second->getName() == name)
				return i->second;

		return 0;
	}
}